import numpy as np
from models.mlp import MLP
from optimizers.factory import OptimizerFactory
from test.test_functions import *

def evaluate_optimizer(optimizer_type, test_function, dim=30, runs=30):
    """评估优化器性能"""
    results = []
    for run in range(runs):
        optimizer = OptimizerFactory.create_optimizer(
            optimizer_type,
            dim=dim,
            pop_size=50,
            max_iter=1000
        )
        best_solution, best_fitness = optimizer.optimize(test_function.evaluate)
        results.append(best_fitness)
        print(f"Run {run+1}/{runs}, Best Fitness: {best_fitness:.6f}")
    return np.mean(results), np.std(results)

def main():
    # 测试函数列表
    test_functions = [
        ('Sphere', Sphere(30)),
        ('Rastrigin', Rastrigin(30)),
        ('Rosenbrock', Rosenbrock(30)),
        ('Ellipsoidal', Ellipsoidal(30)),
        ('Weierstrass', Weierstrass(30)),
        ('Schwefel', Schwefel(30))
    ]
    # 优化器列表
    optimizers = ['de', 'pso', 'ga']
    # 评估结果
    results = {}
    for func_name, func in test_functions:
        print(f"\n评估函数: {func_name}")
        results[func_name] = {}
        for opt_name in optimizers:
            print(f"\n优化器: {opt_name}")
            mean, std = evaluate_optimizer(opt_name, func)
            results[func_name][opt_name] = {'mean': mean, 'std': std}
    # 打印结果
    print("\n评估结果汇总:")
    for func_name in results:
        print(f"\n{func_name}:")
        for opt_name in results[func_name]:
            mean = results[func_name][opt_name]['mean']
            std = results[func_name][opt_name]['std']
            print(f"{opt_name}: {mean:.6f} ± {std:.6f}")

if __name__ == '__main__':
    main() 